package com.example.ping.service;

import com.example.ping.mq.LogProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.reactive.function.client.WebClient;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.time.Duration;

/**
 * @author Jim
 * @create 2025/1/14
 */
@Service
public class PingService {

    private static final String LOCK_FILE_PATH = "rate_limit.lock"; // 锁文件路径
    private static final String REDIS_RATE_LIMIT_KEY = "ping_rate_limit"; // Redis 中的限流键
    private static final int MAX_RPS = 2; // 每秒最大请求数
    private static final int REDIS_TTL_SECONDS = 1; // Redis 键的过期时间（秒）

    @Autowired
    private LogProducer logProducer;

    private WebClient webClient = WebClient.create("http://localhost:8081");

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/sendPing")
    public void sendPing() {
        try (FileChannel channel = new RandomAccessFile(new File(LOCK_FILE_PATH), "rw").getChannel();
             FileLock lock = channel.tryLock()) {
            if (lock != null) {
                // 获取当前的请求计数
                Long currentCount = redisTemplate.opsForValue().increment(REDIS_RATE_LIMIT_KEY);

                if (currentCount != null && currentCount == 1) {
                    // 第一次增加计数时设置过期时间
                    redisTemplate.expire(REDIS_RATE_LIMIT_KEY, Duration.ofSeconds(REDIS_TTL_SECONDS));
                }
                // 检查是否超过了最大请求数(每秒允许的最大请求数量)
                if (currentCount != null && currentCount <= MAX_RPS) {
                    sendRequest();

                } else {
                    log("Request not sent as being rate limited.");
                }
            } else {
                log("Could not acquire lock: Lock is held by another process.");
            }
        } catch (Exception e) {
            log("Error while acquiring lock: " + e.getMessage());
        }
    }

    private void sendRequest() {
        webClient.get().uri("/pong")
                .retrieve()
                .bodyToMono(String.class)
                .doOnNext(response -> log("Request sent & Pong responded: " + response))
                .doOnError(error -> log("Request sent & Pong throttled it: " + error.getMessage()))
                .subscribe();
    }

    private void log(String message) {
        //log.info(LocalDateTime.now() + ": " + message);
        logProducer.sendLog(message);
    }
}
